# -*- coding: utf-8 -*-
import json
import logging
from datetime import datetime
from scrapy.utils.project import get_project_settings
from energyahead.utils.cat_helper import CatalogHelper
from energyahead.utils.order_sku_helper import OrderSkuHelper
from zc_core.model.items import Sku, ItemData, OrderItem, ItemDataSupply
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.common import parse_time
from zc_core.util.encrypt_util import md5
from zc_core.util.sku_id_parser import convert_id2code

logger = logging.getLogger('rule')


# 解析catalog列表
def parse_sub_cat(response):
    cats = list()
    nav_list = json.loads(response.text).get('list', [])
    for nav in nav_list:
        cat = _build_catalog(nav)
        cats.append(cat)

    return cats


def _build_catalog(nav):
    # 将官方的id和code交换，以code为主键
    cat_id = str(nav.get('catalogCode'))
    cat_code = str(nav.get('catalogId', ''))
    cat_name = str(nav.get('catalogName'))
    upper_cat_id = str(nav.get('upperCatalogId', ''))
    level = nav.get('catalogLevel')

    cat = dict()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['upperCatalogId'] = upper_cat_id
    cat['level'] = level
    if level == 4:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 1
    cat['hasChild'] = nav.get('isParent', 0)
    cat['catalogCode'] = cat_code
    cat_id_trim = cat_id
    if level < 4:
        cat_id_trim = cat_id[0:-2 * (4 - level)]
    cat['catalogIdTrim'] = cat_id_trim

    return cat


# 解析sku列表页数
def parse_sku_page(response):
    return json.loads(response.text).get('commodityPageList', {}).get('total', 0)


# 解析sku列表
def parse_sku(response):
    cat_helper = CatalogHelper()
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_list = list()
    skus = json.loads(response.text).get('commodityPageList', {}).get('rows', [])
    for row in skus:
        sku_id = str(row.get('commodityId'))
        sp_id = str(row.get('supplierId'))
        sku_num = row.get('skuNumber', 1)
        if sku_num > 1:
            print('supplierId={}&commodityId={}'.format(sp_id, sku_id))
        sale_price = row.get('lowPrice')
        origin_price = row.get('lowPrice')
        sku_img = row.get('commodityMainPicUrl', '')
        cat4_id = str(row.get('goodsCode', ''))
        cat4_name = row.get('goodsName', '')
        unit = row.get('measureName', '')

        sku = Sku()
        sku['batchNo'] = batch_no
        sku['skuId'] = sku_id
        if sku_num > 1:
            sku['salePrice'] = sale_price
            sku['originPrice'] = origin_price
        sku['supplierId'] = sp_id
        sku['catalog4Id'] = cat4_id
        sku['catalog4Name'] = cat4_name
        cat_helper.fill(sku)
        sku['skuImg'] = sku_img
        sku['unit'] = unit
        sku_list.append(sku)

    return sku_list


# 解析sku列表页数
def parse_back_sku_page(response):
    return json.loads(response.text).get('total', 0)


# 解析sku列表
def parse_front_sku(response):
    meta = response.meta
    sku_id = meta.get('skuId')
    batch_no = meta.get('batchNo')
    data = json.loads(response.text)
    if data and data.get('commodityId', ''):
        spu_id = data.get('upc', None)
        supply = ItemDataSupply()
        supply['skuId'] = sku_id
        supply['spuId'] = spu_id
        supply['batchNo'] = batch_no

        return supply


# 解析sku列表
def parse_back_sku(response):
    cat_helper = CatalogHelper()
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_list = list()
    item_list = list()
    skus = json.loads(response.text).get('rows', [])
    for row in skus:
        sales_status = row.get('publishStatus', 1)
        if sales_status == 1:
            sku_id = str(row.get('commodityId'))
            sku_name = str(row.get('commodityName'))
            spu_id = str(row.get('upc', None))
            material_code = str(row.get('itemId', ''))
            cat4_id = str(row.get('goodsCode', ''))
            cat4_name = row.get('goodsName', '')
            sp_id = str(row.get('supplierId'))
            sp_name = str(row.get('supplierName'))
            sp_sku_id = row.get('thirdCommodityCode', '')
            plat_code = None
            if '得力' in sku_name:
                plat_code = 'deli'
            sp_sku_code = convert_id2code(plat_code, sp_sku_id)
            sale_price = row.get('thirdPartyAgreementPrice', None)
            origin_price = row.get('commodityPrice', None)
            if not sale_price or not origin_price or sale_price <= 0 or origin_price <= 0:
                logger.info('价格异常: sku=%s, sp=%s' % (sku_id, sp_id))
                continue
            sale_price = sale_price / 10000
            origin_price = origin_price / 10000
            unit = row.get('measureName', '')
            sku_img = row.get('commodityMainPicUrl', '')
            brand = row.get('brandName', '')
            on_sale_time = parse_time(row.get('updateTime', ''))
            sku_num = row.get('skuNumber', 1)
            if sku_num > 1:
                logger.info('多个商品: supplierId=%s&commodityId=%s' % (sp_id, sku_id))

            sku = Sku()
            sku['batchNo'] = batch_no
            sku['skuId'] = sku_id
            sku['materialCode'] = material_code
            sku['salePrice'] = sale_price
            sku['originPrice'] = origin_price
            sku['supplierId'] = sp_id
            sku['catalog4Id'] = cat4_id
            sku['catalog4Name'] = cat4_name
            sku['supplierSkuId'] = sp_sku_id
            sku_list.append(sku)

            item = ItemData()
            item['batchNo'] = batch_no
            item['skuId'] = sku_id
            if spu_id:
                item['spuId'] = spu_id
            item['skuName'] = sku_name
            item['materialCode'] = material_code
            item['skuImg'] = sku_img
            item['salePrice'] = sale_price
            item['originPrice'] = origin_price
            item['supplierId'] = sp_id
            item['supplierName'] = sp_name
            item['supplierSkuId'] = sp_sku_id
            item['supplierSkuCode'] = sp_sku_code
            item['unit'] = unit
            item['onSaleTime'] = on_sale_time
            item['catalog4Id'] = cat4_id
            item['catalog4Name'] = cat4_name
            cat_helper.fill(item)
            if brand:
                item['brandName'] = brand
                item['brandId'] = md5(brand)
            item_list.append(item)
        else:
            logger.info('下架: sku=%s, sp=%s' % (row.get('commodityId'), row.get('supplierId')))

    return sku_list, item_list


# 解析ItemData
def parse_item_data(response):
    cat_helper = CatalogHelper()
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    sp_id = meta.get('supplierId')

    data = json.loads(response.text)
    if data:
        bo_list = data.get('thirdPartySkuRspBOList', [])
        if bo_list:
            if len(bo_list) > 1:
                logger.info('多个单品: sku=%s, sp=%s' % (sku_id, sp_id))
            if len(bo_list) == 1:
                sp_sku = bo_list[0]
                result = ItemData()
                result['batchNo'] = batch_no
                result['skuId'] = str(sku_id)
                spu_id = data.get('upc', None)
                if spu_id:
                    if len(spu_id) > 190:
                        # spu过长特殊标记处理
                        spu_id = '{}_{}'.format('MD5', md5(spu_id))
                    result['spuId'] = str(spu_id)
                result['skuName'] = data.get('commodityName', '').strip()
                result['skuImg'] = data.get('commodityMainPicUrl', '')
                # result['catalog3Id'] = str(data.get('guideCatalogId', ''))
                result['catalog4Name'] = data.get('guideCatalogName', '')
                cat_helper.fill(result)
                result['salePrice'] = sp_sku.get('thirdAgreementPrice') / 10000
                result['originPrice'] = sp_sku.get('skuPrice') / 10000
                result['soldCount'] = sp_sku.get('soldNumber', 0)
                result['materialCode'] = sp_sku.get('itemId', None)
                brand = sp_sku.get('brandName', None)
                if brand and brand.strip():
                    result['brandName'] = brand.strip()
                    result['brandId'] = md5(brand.strip())
                result['supplierId'] = sp_sku.get('supplierId', sp_id)
                result['supplierName'] = sp_sku.get('supplierName')
                sp_sku_id = data.get('thirdCommodityCode')
                result['supplierSkuId'] = sp_sku_id
                plat_code = None
                if '得力' in sp_sku.get('supplierName'):
                    plat_code = 'deli'
                result['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)
                # 规格参数
                attrs = sp_sku.get('skuSpecRspBOList', [])
                for attr in attrs:
                    if attr.get('propName').strip() == '型号':
                        model = attr.get('propValue').strip()
                        if model:
                            result['brandModel'] = model[0:190]
                    if not brand and attr.get('propName').strip() == '品牌':
                        brand = attr.get('propValue').strip()
                        if brand:
                            result['brandName'] = brand.strip()
                            result['brandId'] = md5(brand.strip())
                result['genTime'] = datetime.utcnow()
                return result
        else:
            logger.info('单品为空: sku=%s, sp=%s' % (sku_id, sp_id))
    else:
        logger.info('商品异常: sku=%s, sp=%s' % (sku_id, sp_id))


# 解析列表页数
def parse_order_total_page(response):
    return json.loads(response.text).get('total', 0)


# 订单明细
def parse_order_item(response):
    settings = get_project_settings()
    # [-1 草稿, 0 供应商待确认, 1 供应商拒绝, 2 待审批, 3 审批拒绝, 4 待发货, 5 待收货, 6 待结算, 9 交易完成, 10 已取消, 11 部分发货]
    status_list = settings.get('ORDER_STATUS_WHITE_LIST', [4, 5, 6, 9])
    json_list = list()
    order_list = list()
    no_match_order_list = list()
    helper = OrderSkuHelper()
    orders = json.loads(response.text).get('rows', [])
    if orders:
        for row in orders:
            order_sn = str(row.get('sn'))
            order_line = str(row.get('refPoLine'))
            # 记录原始json
            row['_id'] = '{}_{}'.format(order_sn, order_line)
            json_list.append(row)

            # 记录订单明细
            status = row.get('status')
            if status not in status_list:
                continue
            material_code = str(row.get('refItemId'))
            sku_id = helper.get_sku_id(material_code)
            if not sku_id:
                no_match_order_list.append(row)
            else:
                order = OrderItem()
                order_time = parse_time(row.get('createTime'))
                order_code = str(row.get('id'))
                order['id'] = '{}_{}'.format(order_sn, order_line)
                order['orderId'] = order_sn
                order['orderCode'] = order_code
                order['skuId'] = sku_id
                order['count'] = row.get('quantity')
                order['amount'] = row.get('subtotal') / 10000
                order['orderDept'] = row.get('regionalCorporationName')
                order['deptId'] = md5(row.get('purchaseOrgName'))
                order['supplierId'] = row.get('supplierId')
                order['orderUser'] = row.get('createUserName')
                order['orderTime'] = order_time
                order['batchNo'] = time_to_batch_no(order_time)
                order['genTime'] = datetime.utcnow()
                order_list.append(order)

    return order_list, json_list, no_match_order_list
